<template id="section-tree">
  <div>
    <el-form :inline="true" :model="newNode" class="demo-form-inline">
  <el-form-item style="margin-left: 4%;">
    <el-input v-model="newNode.nodeName" placeholder="课时名称"></el-input>
  </el-form-item>
  <el-form-item>
    <el-button type="primary" @click="addNode(newNode)">新增课时</el-button>
  </el-form-item>
</el-form>
    <el-tree
             style="max-width: 2000px; width: 55%;"
             node-key="id"
             :data="data"
             :props="defaultProps"
             :draggable=true
             :default-expanded-keys="expandKeys"
             accordion
             @node-click="handleNodeClick"
    >
    <span slot-scope="{ node, data }"  class="custom-tree-node">
      <span style="margin-right: 25px;">{{node.label}}</span>
      <span v-if="data.parentId != null" >
        <el-button v-if="data.sectionContent && data.sectionContent != ''"
          type="text"
          size="mini"
          @click="preview(data)">
           预览
        </el-button>
        <el-button
          type="text"
          size="mini"
          @click="edit(data)">
           编辑
        </el-button>
        <el-button
            type="text"
            size="mini"
            style="padding-left: 15px;"
            @click="() => open(node, data)">
            更名
          </el-button>
          <el-button
        type="text"
        size="mini"
        @click="rm(data)">
           移除
      </el-button>
      <el-button
        type="text"
        size="mini"
        @click="addDown(data)">
           新增
      </el-button>
        </span>
        <span v-else="data.parentId==null"  class="custom-tree-node">
          <el-button
            type="text"
            size="mini"
            @click="() => open(node, data)">
            更名
          </el-button>
          <el-button
        type="text"
        size="mini"
        @click="rm(data)">
           移除
      </el-button>
      <el-button
        type="text"
        size="mini"
        @click="addDown(data)">
           新增
      </el-button>
        </span>
    </span>
    </el-tree>
    <el-dialog
      :visible.sync="addNodeDialogVisible"
      title="摘要"
      width="500"
      draggable="true"
      overflow="false"
    >
      <el-input
        v-model="inputDialogContent"
        style="width: 560px"
        placeholder="输入摘要"
        clearable
      />
      <el-button style="margin-left: 15px" type="primary" @click="confirmAdd">
        确定
      </el-button>
    </el-dialog>
    <el-dialog
      :visible.sync="rmDialogVisible"
      title="确认移除？"
      draggable="true"
      overflow="false"
    >
      <p>所有相关内容将会清空</p>
      <p>包括课件，教案，资料{{anchorOfOpe && anchorOfOpe.parentId == null? '，讨论': ''}}</p>
      <p>请慎重操作</p>

      <el-button style="margin-left: 15px;margin-top: 20px" type="primary" @click="confirmRm">
        确定
      </el-button>
    </el-dialog>
  </div>

</template>

<script>

import sectiontree from '@/api/sectiontree.js'
import { add } from 'lodash';
export default {

  name: 'SectionTree',
  data() {
    return {
      data: [],
      editDrawerDisplay: false,
      drawerWidth: '80%',
      editingSectionId: null,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      rmDialogVisible: false,
      addNodeDialogVisible: false,
      inputDialogVisible: false,
      inputDialogContent: '',
      anchorOfOpe: null,
      expandKeys: [],
      newNode:{
        nodeName : ''
      }
    };
  },
  mounted() {
    this.fetchSectionTree()
  },
  methods: {
    fetchSectionTree() {
        sectiontree.fetchSectionTree().then(resp => {
          this.data = resp.data;
          if (this.anchorOfOpe) {
            this.expandKeys = [this.anchorOfOpe.id]
            this.anchorOfOpe = null;
          }
        }).catch(error => {
            console.log(error);
        });
    },
    handleNodeClick(data) {
      console.log("handleNodeClick", data);
      if (data.parentId === null) {
        this.$emit('lv1Clk', data);
      }
    },
    open(node, data) {
        	this.$prompt('请输入章节名称', '提示', {
          	confirmButtonText: '确定',
          	cancelButtonText: '取消',
        }).then(({ value }) => {
        	console.log(data);
        	data.label = value
          this.$message({
            type: 'success',
            message: '你输入的章节名称是: ' + value,
           
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          });       
        })
      },
    preview(data) {
      console.log("ST HTML:", data.sectionContent)
      this.$emit('preview', data.sectionContent, data.label);
    },
    edit(data){
      this.$emit('editingSection', data);
      this.anchorOfOpe = data;
    },
    rm(data) {
      this.anchorOfOpe = data;
      this.rmDialogVisible = true;
    },
    rename(data) {
      if(edit){
        targetName='123';

      }
        this.renameVisible = !this.edit;
    },
    addDown(data) {
      console.log("addDown", data)
      this.anchorOfOpe = data;
      this.inputDialogVisible = true;
    },
    addNode(newNode) {
      console.log("addNode", newNode)
      sectiontree.addTopNode(this.newNode.nodeName).then(resp => {
          this.data = resp.data;
          if (resp.data.code==0) {
            logger.info("addNode", resp.data)
          }
        }).catch(error => {
            console.log(error);
        });
      location.reload();
    },
    addNodeDialog() {
      console.log("addNodeDialog")
      this.addNodeDialogVisible = true;
    },
    confirmRm() {
      let anchorId = this.anchorOfOpe.id;
      let anchorParentId = this.anchorOfOpe.parentId;
      console.log('删除前数据',this.data)
      let levelData = treeForeach(this.data, (candidate) => {
        return anchorId === candidate.id;
      });

      if (levelData) {
        for(let i = 0; i　< levelData.length; i++) {
          if (levelData[i].id === anchorId) {
            levelData.splice(i,1)
            break;
          }
        }

        sectiontree.saveSectionTree(this.data).then(resp => {
          this.fetchSectionTree()
          if (anchorParentId === null) {
            this.$emit('unfoucusSection');
          }
          this.rmDialogVisible = false;
        })
      } else {
        console.warn("未找到对应levelData?? anchorOfOpe:",this.anchorOfOpe, '\ndata:', this.data)
      }
    },

    confirmAdd() {

      let title =  this.inputDialogContent;

      let anchorId = this.anchorOfOpe.id;
      let anchorParentId = this.anchorOfOpe.parentId;

      let levelData = treeForeach(this.data, (candidate) => {
         return anchorId === candidate.id;
      });

      if (levelData) {
        for(let i = 0; i　< levelData.length; i++) {
          if (levelData[i].id === anchorId) {
            levelData.splice(i + 1,0, {
              label: title,
              parentId: anchorParentId,

            })

            break;
          }
        }

        sectiontree.saveSectionTree(this.data).then(resp => {
          this.fetchSectionTree()
          this.inputDialogVisible = false;
          this.inputDialogContent = '';
        })
      } else {
        console.warn("未找到对应levelData?? anchorOfOpe:",this.anchorOfOpe, '\ndata:', this.data)
      }


    }
  }
};


function treeForeach (tree, predictFunc) {

  if (tree) {
    for(let i = 0; i　< tree.length; i++) {
      if (predictFunc(tree[i])) {
        return tree;
      }
      if (tree[i].children ) {
        // 遍历子树
        let res = treeForeach(tree[i].children, predictFunc)
        if (res) {
          return res;
        }
      }
    }
  }
}
</script>

<style>
  .custom-tree-node {
    flex: 1;
    /* display: flex; */
    align-items: center;
    justify-content: space-between;
    font-size: 18px;
    padding-left: 500 px;
  }
</style>

